﻿using DailyPoetryH.Library.Models;
using System.Linq.Expressions;
using DailyPoetryH.Library.Services;
using Microsoft.AspNetCore.Components;

namespace DailyPoetryH.Library.Pages;

public partial class Result {
    [Parameter]
    public string Ticket { get; set; } = string.Empty;

    private Expression<Func<Poetry, bool>> _where = p => true;

    public const string Loading = "正在载入";

    public const string NoResult = "没有满足条件的结果";

    public const string NoMoreResult = "没有更多结果";

    private string _status = string.Empty;

    public const int PageSize = 20;

    private List<Poetry> _poetries = new();

    protected override async Task OnAfterRenderAsync(bool firstRender) {
        if (!firstRender) {
            return;
        }

        if (string.IsNullOrWhiteSpace(Ticket)) {
            return;
        }

        var parameter =
            _parcelBoxService.Get(Ticket) as Expression<Func<Poetry, bool>>;

        if (parameter is null) {
            return;
        }

        _poetries.Clear();
        _where = parameter;
        await LoadMoreAsync();
    }

    private async Task LoadMoreAsync() {
        _status = Loading;
        var poetries =
            await _poetryStorage.GetPoetriesAsync(_where, _poetries.Count,
                PageSize);
        _status = string.Empty;
        _poetries.AddRange(poetries);

        if (poetries.Count() < PageSize) {
            _status = NoMoreResult;
        }

        if (!poetries.Any() && _poetries.Count == 0) {
            _status = NoResult;
        }
    }

    private void OnClick(Poetry poetry) =>
        _navigationService.NavigateTo(
            $"{NavigationServiceConstants.DetailPage}/{poetry.Id}");
}